package com.enjoy.xbase.db.impi;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

import com.enjoy.xbase.db.annotation.AnnFiled;
import com.enjoy.xbase.db.handle.IInsert;
import com.enjoy.xbase.db.tools.DBTools;
import com.enjoy.xbase.db.tools.LogDb;

import java.lang.reflect.Field;

public class MInsert implements IInsert {
    private SQLiteDatabase db;

    public MInsert(SQLiteDatabase db) {
        this.db = db;
    }

    private static void put(ContentValues contentValues, String columnName, Object val) {
        if (val == null) return;
        if (val instanceof Integer) {
            contentValues.put(columnName, (Integer) val);
        } else if (val instanceof Long) {
            contentValues.put(columnName, (Long) val);
        } else if (val instanceof String) {
            contentValues.put(columnName, (String) val);
        } else if (val instanceof Float) {
            contentValues.put(columnName, (Float) val);
        } else if (val instanceof Double) {
            contentValues.put(columnName, (Double) val);
        } else {
            throw new RuntimeException("数据格式未知");
        }
    }
    @Override
    public int insert(Object data) {
        Field[] fields = data.getClass().getDeclaredFields();
        ContentValues contentValues = new ContentValues();
        try {
            for (Field _field : fields) {
                AnnFiled annFiled = _field.getAnnotation(AnnFiled.class);
                //主键不赋值
                if (annFiled != null && !"id".equals(annFiled.columnName())) {
                    _field.setAccessible(true);
                    put(contentValues, annFiled.columnName(), _field.get(data));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            LogDb.err("数据库异常", "插入异常" + e.toString());
        }
        if (this.db == null) {
            return -1;
        }
        return (int) db.insert(DBTools.getTabName(data), null, contentValues);
    }
}
